package com.originskyseed.platform.user.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.originskyseed.platform.common.annotation.SysLog;
import com.originskyseed.platform.common.api.config.LoginConfig;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.config.bean.ConfigManager;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.core.util.bean.ExportExcelUtil;
import com.originskyseed.platform.core.util.bean.PrimaryKeyGeneratorUtil;
import com.originskyseed.platform.recruit.model.RecruitRelateRecommend;
import com.originskyseed.platform.recruit.service.IRecruitRelateRecommendService;
import com.originskyseed.platform.role.model.Role;
import com.originskyseed.platform.role.model.RoleRelUser;
import com.originskyseed.platform.role.service.IRoleRelUserService;
import com.originskyseed.platform.role.service.IRoleService;
import com.originskyseed.platform.user.i18n.RegisterResponseMsg;
import com.originskyseed.platform.user.i18n.UserResponseMsg;
import com.originskyseed.platform.user.model.Dept;
import com.originskyseed.platform.user.model.TaskSelectSaleManVO;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IDeptService;
import com.originskyseed.platform.user.service.IUserInfoService;
import com.originskyseed.platform.user.vo.request.UserInfoListRequestVO;

/**
 * 用户信息表Controller类（OSI_USER_INFO）
 *
 * @author LiangMingHui
 */
@Controller
@RequestMapping("/userInfo")
@BaseLocaleResource(localeFileName = "i18n_user")
public class UserInfoController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(UserInfoController.class);

	@DubboReference
	private IUserInfoService userInfoService;

	@DubboReference
	private IDeptService deptService;

	@DubboReference
	private IRoleService roleService;

	@DubboReference
	private IRoleRelUserService roleRelUserService;

	@DubboReference
	private IRecruitRelateRecommendService recruitRelateRecommendService;

	/**
	 * 分页查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/userList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody userList(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 当前登录用户
			UserInfo currentUserInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			if(currentUserInfo==null)
			{
				result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()),null, null);
                return  result;
			}
			// 请求对象
			UserInfoListRequestVO requestVO = this.getParameterBean(UserInfoListRequestVO.class);
			// 部门code
			String parentCode = this.getParameterString("parentCode", null);
			// 如果部门code为空，则查询当前登录用户的部门code
			if(StringUtils.isBlank(parentCode)){
				Dept dept = this.deptService.selectByPrimaryKey(currentUserInfo.getDeptId());
				if(dept!=null){
					parentCode = dept.getCode();
				}
			}
			Map<String, Object> map = requestVO.toMap();
			// 查询所有的子集
			if (StringUtils.isNotBlank(parentCode)) {
				Dept dept = this.deptService.selectByCode(parentCode);
				if (dept != null) {
					List<String> list = new ArrayList<>();
					list.add(dept.getId());
					selectDeptSon(parentCode, list);
					map.put("list", list);
				}
			}

			// 获得所有的子部门
			/*List<String> array = new ArrayList<>();
			Dept dept = this.deptService.selectByPrimaryKey(currentUserInfo.getDeptId());
			array.add(dept.getId());
			this.selectSonId(dept.getCode(), array);
			map.put("array", array);*/
            if(requestVO.getPageNo()<0)
			{
				requestVO.setPageNo(1);
				logger.error("==selectListRelRoleByPage===requestVO=="+requestVO);
			}
			// 分页查询
			BasePage<UserInfo> page = new BasePage<UserInfo>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.userInfoService.selectListRelRoleByPage(map, page);
			for (UserInfo userInfo : page.getResults()) {
				String phone = userInfo.getPhone();
				String idCardNum = userInfo.getIdCardNum();
				if (phone != null && StringUtils.isNotBlank(phone)) {
					if(phone.length()>=11) {
						userInfo.setPhone(phone.substring(0, 3) + "****" + phone.substring(7, 11));
					}
				}
				if (idCardNum != null && StringUtils.isNotBlank(idCardNum)) {
					if(idCardNum.length()>=14) {
						userInfo.setIdCardNum(idCardNum.substring(0, 14) + "****");
					}
				}
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 选择人员信息_分页查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectMaintainList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody selectMaintainList(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			UserInfoListRequestVO requestVO = this.getParameterBean(UserInfoListRequestVO.class);

			// 分页查询
			BasePage<UserInfo> page = new BasePage<UserInfo>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.userInfoService.selectMaintainListByPage(requestVO.toMap(), page);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 任务广场中选择业务员/主播信息_分页查询 用户类型 1业务员 2主播
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectSaleManOrAnchorInfoList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize", "userType" }) // 用户类型 1主播 2业务员
	public BaseResponseBody selectSaleManOrAnchorInfoList(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			UserInfoListRequestVO requestVO = this.getParameterBean(UserInfoListRequestVO.class);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 分页查询
			BasePage<TaskSelectSaleManVO> page = new BasePage<TaskSelectSaleManVO>(requestVO.getPageNo(), requestVO.getPageSize());
			if (userInfo.getSourceSys() == 0 || (requestVO.getType() != null && requestVO.getType() == 1)) { // 全平台
				if (requestVO.getUserType() == 1) {
					// 主播
					page = this.userInfoService.selectMaintainAnchorListByPage(requestVO.toMap(), page);
				} else {
					// 业务员
					page = this.userInfoService.selectSaleInfoListByPage(requestVO.toMap(), page);
				}

			} else { // 体系下
				if (userInfo.getType() != 6 || userInfo.getType() != 11) {
					// 查询所有的子节点
					List<String> deptIdList = new ArrayList<>();
					Dept dept = this.deptService.selectByPrimaryKey(userInfo.getDeptId());
					if (dept != null) {
						// 如果是小组
						/*if ((dept.getSourceSys() == 2 && dept.getType() == 10) || (dept.getSourceSys() == 1 && dept.getType() == 3)) {
							deptIdList.add(dept.getId());
						} else {
							this.selectDeptSon(dept.getCode(), deptIdList);
						}*/
						deptIdList.add(dept.getId());
						this.selectDeptSon(dept.getCode(), deptIdList);
						if(requestVO.getPromotionTask() != null && requestVO.getPromotionTask() == 1){
							// 业务员
							List<String> userIdList = this.userInfoService.selectSalesmanUserIdsByDeptIds(deptIdList);
							if(userIdList==null)
							{
								userIdList=new ArrayList<>();
							}
							userIdList.add(userInfo.getId());
							requestVO.setUserIdList(userIdList);
							page = this.userInfoService.selectPromotionTaskAnchorListByPage(requestVO.toMap(), page);
						}else if (requestVO.getUserType() == 1) {
							// 主播
							List<String> userIdList = this.userInfoService.selectAnchorIdsByDeptIds(deptIdList);
							if(userIdList==null)
							{
								userIdList=new ArrayList<>();
							}
							userIdList.add(userInfo.getId());
							requestVO.setUserIdList(userIdList);
							page = this.userInfoService.selectMaintainAnchorListByPage(requestVO.toMap(), page);
						} else {
							// 业务员
							List<String> userIdList = this.userInfoService.selectSalesmanUserIdsByDeptIds(deptIdList);
							if(userIdList==null)
							{
								userIdList=new ArrayList<>();
							}
							userIdList.add(userInfo.getId());
							requestVO.setUserIdList(userIdList);
							page = this.userInfoService.selectSaleInfoListByPage(requestVO.toMap(), page);
						}
					}
				} else {
					return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.LIMIT_USER_ERROR.getMsg()), null);
				}

			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/userSave.json", method = RequestMethod.POST)
	public BaseResponseBody userSave(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			UserInfo creatUserInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 请求对象
			UserInfo userInfo = this.getParameterBean(UserInfo.class);

			// 判断账号是否符合规则
			if (!userInfo.getAccount().matches("^[0-9A-Za-z]{1,16}$")) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RegisterResponseMsg.ACCOUNT_RULE_ERROR.getMsg()), false);
			}
			// 判断账号是否存在
			if (userInfoService.accountExist(userInfo)) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RegisterResponseMsg.ACCOUNT_EXIST.getMsg()), false);
			}
			// 判断名称是否存在
			if (userInfoService.nameExist(userInfo)) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RegisterResponseMsg.NAME_EXIST_ERROR.getMsg()), false);
			}

			// 判断密码
			if (StringUtils.isNotBlank(userInfo.getPassword()) && userInfo.getPassword().length() < 8) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RegisterResponseMsg.PASSWORD_LENGTH_ERROR.getMsg()), false);
			} else if (StringUtils.isNotBlank(userInfo.getPassword()) && !userInfo.getPassword().matches("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[~!@#$%^&*()_+`\\-={}:\";'<>?,.\\/]).{8,16}$")) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RegisterResponseMsg.PASSWORD_SIMPLE_ERROR.getMsg()), false);
			}

			if (StringUtils.isNotEmpty(userInfo.getDeptId())) {
				Dept dept = this.deptService.selectByPrimaryKey(userInfo.getDeptId());
				userInfo.setSourceSys(dept.getSourceSys());
			}

			if (StringUtils.isNotBlank(userInfo.getOtherAccount())) {
				UserInfo userInfo1 = this.userInfoService.selectByOtherAccount(userInfo.getOtherAccount());
				if (userInfo1 != null && !userInfo1.getId().equals(userInfo.getId())) {
					return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.OTHER_ACCOUNT_EXIST_ERROR.getMsg()), false);
				}
			}

			if (StringUtils.isNotBlank(userInfo.getId())) {
				// 如果是带*的则不修改
				if(StringUtils.isNotBlank(userInfo.getIdCardNum()) && userInfo.getIdCardNum().contains("****")){
					userInfo.setIdCardNum(null);
				}
				if(StringUtils.isNotBlank(userInfo.getPhone()) && userInfo.getPhone().contains("****")){
					userInfo.setPhone(null);
				}
				// 判断手机号是否正确
				if(StringUtils.isNotBlank(userInfo.getPhone()) && !userInfo.getPhone().matches("^1(3|4|5|6|7|8|9)\\d{9}$")){
					return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RegisterResponseMsg.PHONE_FORMAT_ERROR.getMsg()), false);
				}

				// 密码加密
				if (StringUtils.isNotBlank(userInfo.getPassword())) {
					userInfo.setPassword(DigestUtils.md5DigestAsHex(userInfo.getPassword().getBytes()));
				}
				if (StringUtils.isNotBlank(userInfo.getPermissionPassword())) {
					userInfo.setPermissionPassword(DigestUtils.md5DigestAsHex(userInfo.getPermissionPassword().getBytes()));
				}
				this.userInfoService.updateByPrimaryKeySelective(userInfo);
			} else {
				// 判断手机号是否正确
				if(!userInfo.getPhone().matches("^1(3|4|5|6|7|8|9)\\d{9}$")){
					return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RegisterResponseMsg.PHONE_FORMAT_ERROR.getMsg()), false);
				}
				Integer prority = this.userInfoService.selectPrority();
				if (prority == null) {
					userInfo.setPriority(0);
				} else {
					userInfo.setPriority(prority + 1);
				}
				userInfo.setStatus(1);
				userInfo.setIsEconomicContract(0);
				userInfo.setIsDel(0);
				userInfo.setCreator(creatUserInfo.getName());
				userInfo.setCreatorId(creatUserInfo.getId());
				userInfo.setUserNum(this.userInfoService.selectUserNum());
				userInfo.setPassword(DigestUtils.md5DigestAsHex(userInfo.getPassword().getBytes()));
				// 获取邀请码前缀
				String recommendInitial = getDeptRecommendInitial(userInfo.getDeptId());
				userInfo.setOwnInvitationCode(createOwnInvitationCode(recommendInitial));
				if (StringUtils.isNotBlank(userInfo.getPermissionPassword())) {
					userInfo.setPermissionPassword(DigestUtils.md5DigestAsHex(userInfo.getPermissionPassword().getBytes()));
				}
				if (userInfo.getBasePay() == null) {
					userInfo.setBasePay(BigDecimal.ZERO);
				}

				this.userInfoService.insertSelective(userInfo);
			}
			if (StringUtils.isNotEmpty(userInfo.getRoleId())) {
				List<String> list = new ArrayList<>();
				list.add(userInfo.getRoleId());
				this.roleRelUserService.deleteAndInsertByUserId(userInfo.getId(), list);
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), userInfo);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 根据id查询详情
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectUserById.json", method = RequestMethod.POST)
	@RequiredParams(names = { "id" })
	public BaseResponseBody selectUserById(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String id = this.getParameterString("id", null);

			UserInfo userInfo = this.userInfoService.selectByPrimaryKey(id);
			Dept dept = this.deptService.selectByPrimaryKey(userInfo.getDeptId());
			if (dept != null) {
				userInfo.setDeptName(dept.getName());
			}
			List<Role> roleList = this.roleService.selectByUserId(id);
			if (roleList.size() > 0) {
				Role role = roleList.get(0);
				userInfo.setRoleId(role.getId());
				userInfo.setRoleName(role.getName());
				userInfo.setRoleCode(role.getCode());
			}
			String phone = userInfo.getPhone();
			String idCardNum = userInfo.getIdCardNum();
			if (phone != null && StringUtils.isNotBlank(phone)) {
				if(phone.length()>=11) {
					userInfo.setPhone(phone.substring(0, 3) + "****" + phone.substring(7, 11));
				}
			}
			if (idCardNum != null && StringUtils.isNotBlank(idCardNum)) {
				if(idCardNum.length()>=14) {
					userInfo.setIdCardNum(idCardNum.substring(0, 14) + "****");
				}
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_SUCCESS.getMsg()), userInfo);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 批量修改用户状态
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updateStatus.json")
	@RequiredParams(names = { "ids", "status" })
	public BaseResponseBody updateStatus(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			String[] ids = this.getParameterArray("ids", null);
			Integer status = this.getParameterInteger("status", null);

			this.userInfoService.updateStatus(Arrays.asList(ids), status);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}


	/**
	 * 修改绑定的app账号
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updateOtherAccount.json")
	@RequiredParams(names = { "id", "otherAccount" })
	public BaseResponseBody updateOtherAccount(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			String id = this.getParameterString("id", null);
			String otherAccount = this.getParameterString("otherAccount", null);

			UserInfo userInfo = new UserInfo();
			userInfo.setId(id);
			userInfo.setOtherAccount(otherAccount);

			UserInfo userInfo1 = this.userInfoService.selectByOtherAccount(otherAccount);
			if (userInfo1 != null && !userInfo1.getId().equals(id)) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.OTHER_ACCOUNT_EXIST_ERROR.getMsg()), false);
			}
			this.userInfoService.updateByPrimaryKeySelective(userInfo);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 批量修改部门状态
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updatePassword.json")
	@RequiredParams(names = { "id", "password" })
	public BaseResponseBody updatePassword(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			String id = this.getParameterString("id", null);
			String password = this.getParameterString("password", null);
			UserInfo userInfo = this.userInfoService.selectByPrimaryKey(id);
			// 判断密码
			if (password.length() < 8) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RegisterResponseMsg.PASSWORD_LENGTH_ERROR.getMsg()), false);
			} else if (!password.matches("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[~!@#$%^&*()_+`\\-={}:\";'<>?,.\\/]).{8,16}$")) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RegisterResponseMsg.PASSWORD_SIMPLE_ERROR.getMsg()), false);
			} else if (DigestUtils.md5DigestAsHex(password.getBytes()).equals(userInfo.getPassword())) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RegisterResponseMsg.NEW_OLD_PASSWORD_AGREEMENT.getMsg()), false);
			}

			UserInfo updateUserInfo = new UserInfo();
			updateUserInfo.setId(id);
			updateUserInfo.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
			updateUserInfo.setUpdateTime(new Date());
			updateUserInfo.setUpdatePassTime(new Date());
			this.userInfoService.updateByPrimaryKeySelective(updateUserInfo);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 用户绑定角色页面
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/userInfoBindRoleList.json")
	public BaseResponseBody userInfoBindRoleList(HttpServletRequest request) {
		BaseResponseBody result = null;
		Map<String, Object> model = new HashMap<String, Object>();
		try {
			// 请求参数
			String id = this.getParameterString("id", null);

			if (StringUtils.isNotBlank(id)) {
				UserInfo userInfo = this.userInfoService.selectByPrimaryKey(id);
				model.put("userInfo", userInfo);
				Role role = new Role();
				List<Role> roleList = this.roleService.selectList(role);
				model.put("roleList", roleList);
				List<RoleRelUser> roleRelUserList = this.roleRelUserService.selectByUserId(id);
				model.put("roleRelUserList", roleRelUserList);
				result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), model);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 用户信息绑定角色
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/userInfoBindRole.json")
	@RequiredParams(names = { "userId" })
	public BaseResponseBody userInfoBindRole(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String userId = this.getParameterString("userId", null);
			String[] roleIds = this.getParameterArray("roleIds", new String[] {});

			List<String> roleIdList = Arrays.asList(roleIds);
			this.roleRelUserService.deleteAndInsertByUserId(userId, roleIdList);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 修改置顶信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateIsTop.json", method = RequestMethod.POST)
	@RequiredParams(names = { "id" })
	public BaseResponseBody updateIsTop(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String id = this.getParameterString("id", null);

			UserInfo userInfo = new UserInfo();
			userInfo.setId(id);
			userInfo.setIsTop(1);
			userInfo.setTopTime(new Date());
			this.userInfoService.updateByPrimaryKeySelective(userInfo);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 升序降序
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateUpOrDown.json", method = RequestMethod.POST)
	@RequiredParams(names = { "id", "upOrDown", "prority" })
	public BaseResponseBody updateUpAndDown(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String id = this.getParameterString("id", null);
			Integer upOrDown = this.getParameterInteger("upOrDown", null);

			// 获取用户信息,获取当前的优先级
			UserInfo queryUserInfo = this.userInfoService.selectByPrimaryKey(id);
			Integer currentPrority = queryUserInfo.getPriority();
			Integer updatePrority = currentPrority;

			// 等于0是升序 1是降序
			if (upOrDown == 0) {
				currentPrority += 1;
			} else {
				currentPrority -= 1;
			}

			// 替换当前的优先级
			UserInfo userInfo = this.userInfoService.selectUserByPrority(currentPrority);
			if (userInfo != null) {
				userInfo.setPriority(updatePrority);
			}

			UserInfo updatePaper = new UserInfo();
			updatePaper.setId(id);
			updatePaper.setPriority(currentPrority);
			if (userInfo != null) {
				this.userInfoService.updatePrority(userInfo, updatePaper);
			} else {
				this.userInfoService.updateByPrimaryKeySelective(updatePaper);
			}

			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), e.getMessage(), null);
		}
		return result;
	}


	/**
	 * 批量修改主播是否签约
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updateQuitStatus.json")
	@RequiredParams(names = { "id", "isQuit" })
	public BaseResponseBody updateQuitStatus(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			String id = this.getParameterString("id", null);
			Integer isQuit = this.getParameterInteger("isQuit", null);

			UserInfo userInfo = new UserInfo();
			userInfo.setId(id);
			userInfo.setIsQuit(isQuit);
			userInfo.setQuitTime(new Date());
			userInfo.setUpdateTime(new Date());
			this.userInfoService.updateByPrimaryKeySelective(userInfo);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}


	/**
	 * 用户查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectUserList.json", method = RequestMethod.POST)
	public BaseResponseBody selectUserList(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			UserInfo userInfo = this.getParameterBean(UserInfo.class);

			// 查询用户列表
			List<UserInfo> userInfoList = this.userInfoService.selectList(userInfo);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), userInfoList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 判断权限密码是否正确
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/judgePermissionPassword.json", method = RequestMethod.POST)
	public BaseResponseBody judgePermissionPassword(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			String permissionPassword = this.getParameterString("permissionPassword", null);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);

			if (DigestUtils.md5DigestAsHex(permissionPassword.getBytes()).equals(userInfo.getPermissionPassword())) {
				return new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.PERMISSION_PASSWORD_SUCCESS.getMsg()), true);
			} else {
				result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.PERMISSION_PASSWORD_ERROR.getMsg()), false);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 判断是否新用户登录
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/isNewUserLogin.json")
	public BaseResponseBody isNewUserLogin(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class); // 获取当前用户信息
			if (null != userInfo) {
				// 判断用户最后登录时间是否为空
				// UserInfo newUserInfo = this.userInfoService.selectByPrimaryKey(userInfo.getId());
				Boolean iSNewUserLogin = false; // 不是
				if (userInfo.getIsFirstLogin() != null && userInfo.getIsFirstLogin() == 1) {
					iSNewUserLogin = true;
				}
				result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.SELECT_DATA_SUCCESS.getMsg()), iSNewUserLogin);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.SELECT_DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 判断是否当天首次登录
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/isSameDayFirstLogin.json")
	public BaseResponseBody isSameDayFirstLogin(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class); // 获取当前用户信息
			if (null != userInfo) {
				String phone = null; // 不是
				if (userInfo.getIsSameDayFirstLogin() != null && userInfo.getIsSameDayFirstLogin() == 1) {
					phone = userInfo.getPhone();
				}
				result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.SELECT_DATA_SUCCESS.getMsg()), phone);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.SELECT_DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 判断是否要强制修改密码
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/isForcePasswordChange.json")
	public BaseResponseBody isForcePasswordChange(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class); // 获取当前用户信息
			// 最大修改密码间隔时间
			LoginConfig loginConfig = ConfigManager.getInstance().parseObject(LoginConfig.class);
			Integer maxUpdatePasswordDate = loginConfig.getMaxUpdatePasswordDate();
			Date date = new Date();
			Date updatePassTime = userInfo.getUpdatePassTime();
			if (updatePassTime == null) {
				updatePassTime = userInfo.getCreateTime();
			}
			// 得到相隔的天数
			long day = (date.getTime() - updatePassTime.getTime()) / (24 * 60 * 60 * 1000);
			// 相隔的天数大于最大的登录间隔天数
			if (day > maxUpdatePasswordDate) {
				return new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.SELECT_DATA_SUCCESS.getMsg()), true);
			} else {
				return new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.SELECT_DATA_SUCCESS.getMsg()), false);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.SELECT_DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 新用户登录填写邀请码
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/newUserInvitationCodeSave.json", method = RequestMethod.POST)
	@RequiredParams(names = { "invitationCode" })
	public BaseResponseBody newUserInvitationCodeSave(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			String invitationCode = this.getParameterString("invitationCode", null);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class); // 获取当前用户信息
			if (null != userInfo && StringUtils.isNotEmpty(invitationCode)) {
				userInfo.setInvitationCode(invitationCode);
				this.userInfoService.updateByPrimaryKeySelective(userInfo);

				UserInfo invitationUserInfo = this.userInfoService.selectByOwnInvitationCode(invitationCode);
				if (invitationUserInfo != null) {
					RecruitRelateRecommend recruitRelateRecommend = new RecruitRelateRecommend();
					recruitRelateRecommend.setAccount(userInfo.getAccount());
					recruitRelateRecommend.setName(userInfo.getName());
					recruitRelateRecommend.setRecommendId(invitationUserInfo.getId());
					recruitRelateRecommend.setRecommendAccount(invitationUserInfo.getAccount());
					recruitRelateRecommend.setRecommendName(invitationUserInfo.getName());
					recruitRelateRecommend.setIsReview(0);
					this.recruitRelateRecommendService.insertSelective(recruitRelateRecommend);
				}
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_CODE_SAVE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_CODE_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 获取用户信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/userInfo.json")
	public BaseResponseBody getUserInfo(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class); // 获取当前用户信息
			if (null != userInfo) {
				// 获取最新的数据
				UserInfo newUserInfo = this.userInfoService.selectByPrimaryKey(userInfo.getId());
				newUserInfo.setRoleId(userInfo.getRoleId());
				newUserInfo.setRoleCode(userInfo.getRoleCode());
				newUserInfo.setRoleName(userInfo.getRoleName());
				// 查询部门
				if (StringUtils.isNotEmpty(newUserInfo.getDeptId())) {
					Dept dept = this.deptService.selectByPrimaryKey(newUserInfo.getDeptId());
					if (dept != null) {
						newUserInfo.setDeptName(dept.getName());
					}
				}
				// 脱密
				String phone = newUserInfo.getPhone();
				String idCardNum = newUserInfo.getIdCardNum();
				if (phone != null && StringUtils.isNotBlank(phone)) {
					if(phone.length()>=11) {
						newUserInfo.setPhone(phone.substring(0, 3) + "****" + phone.substring(7, 11));
					}
				}
				if (idCardNum != null && StringUtils.isNotBlank(idCardNum)) {
					if(idCardNum.length()>=14) {
						newUserInfo.setIdCardNum(idCardNum.substring(0, 14) + "****");
					}
				}
				result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), newUserInfo);
			} else {
				result = new BaseResponseBody(true, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), false);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()) + e.getMessage(), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 修改信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateUser.json", method = RequestMethod.POST)
	public BaseResponseBody updateUser(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			UserInfo creatUserInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 请求对象
			UserInfo userInfo = this.getParameterBean(UserInfo.class);
			userInfo.setId(creatUserInfo.getId());

			// 判断账号是否符合规则
			if (StringUtils.isNotBlank(userInfo.getAccount()) && !userInfo.getAccount().matches("^[0-9A-Za-z]{1,16}$")) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RegisterResponseMsg.ACCOUNT_RULE_ERROR.getMsg()), false);
			}
			// 判断账号是否存在
			if (StringUtils.isNotBlank(userInfo.getAccount()) && userInfoService.accountExist(userInfo)) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RegisterResponseMsg.ACCOUNT_EXIST.getMsg()), false);
			}

			// 判断密码
			if (StringUtils.isNotBlank(userInfo.getPassword()) && userInfo.getPassword().length() < 8) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RegisterResponseMsg.PASSWORD_LENGTH_ERROR.getMsg()), false);
			} else if (StringUtils.isNotBlank(userInfo.getPassword()) && !userInfo.getPassword().matches("^(?=.*[0-9])(?=.*[a-zA-Z])[0-9A-Za-z!@#$%^&*,\\.]{8,16}$")) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RegisterResponseMsg.PASSWORD_SIMPLE_ERROR.getMsg()), false);
			}

			if (StringUtils.isNotEmpty(userInfo.getDeptId())) {
				Dept dept = this.deptService.selectByPrimaryKey(userInfo.getDeptId());
				userInfo.setSourceSys(dept.getSourceSys());
				userInfo.setType(dept.getType());
			}
			if (userInfo.getPassword() != null) {
				userInfo.setPassword(DigestUtils.md5DigestAsHex(userInfo.getPassword().getBytes()));
			}
			if (userInfo.getPermissionPassword() != null) {
				userInfo.setPermissionPassword(DigestUtils.md5DigestAsHex(userInfo.getPermissionPassword().getBytes()));
			}

			// 如果是带*的则不修改
			if(StringUtils.isNotBlank(userInfo.getIdCardNum()) && userInfo.getIdCardNum().contains("****")){
				userInfo.setIdCardNum(null);
			}
			if(StringUtils.isNotBlank(userInfo.getPhone()) && userInfo.getPhone().contains("****")){
				userInfo.setPhone(null);
			}
			this.userInfoService.updateByPrimaryKeySelective(userInfo);

			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), userInfo);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 批量修改主播是否签约
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updateIsEconomic.json")
	@RequiredParams(names = { "ids", "isSign" })
	public BaseResponseBody updateIsEconomic(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			String[] ids = this.getParameterArray("ids", null);
			Integer isSign = this.getParameterInteger("isSign", null);

			this.userInfoService.updateIsEconomic(Arrays.asList(ids), isSign);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 导出用户Excel
	 *
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping("/exportUserExcel.json")
	public void exportUserExcel(HttpServletRequest request, HttpServletResponse response) {
		try {
			UserInfo userInfo = this.getParameterBean(UserInfo.class);
			List<UserInfo> userInfoList = this.userInfoService.selectExportExcelList(userInfo);
			// excel标题
			String[] title = { "员工编号", "员工名称", "员工账号", "手机号码", "状态", "部门编码", "部门名称","成本", "创建时间", "创建人" };

			// excel文件名
			String fileName = "员工信息.xls";
			// sheet名
			String sheetName = "员工";
			String[][] values = new String[userInfoList.size()][];

			if (userInfoList != null && userInfoList.size() > 0) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				for (int i = 0; i < userInfoList.size(); i++) {
					values[i] = new String[title.length];
					UserInfo obj = userInfoList.get(i);
					values[i][0] = obj.getUserNum() == null ? "" : obj.getUserNum();
					values[i][1] = obj.getName() == null ? "" : obj.getName();
					values[i][2] = obj.getAccount() == null ? "" : obj.getAccount();
					values[i][3] = obj.getPhone() == null ? "" : obj.getPhone();
					if (obj.getStatus() != null) {
						if (obj.getStatus() == 1) {
							values[i][4] = "启用";
						} else if (obj.getStatus() == 2) {
							values[i][4] = "禁用";
						} else if (obj.getStatus() == 4) {
							values[i][4] = "锁定";
						} else if (obj.getStatus() == 5) {
							values[i][4] = "冻结";
						}
					} else {
						values[i][4] = "";
					}
					values[i][5] = obj.getDeptCode() == null ? "" : obj.getDeptCode();
					values[i][6] = obj.getDeptName() == null ? "" : obj.getDeptName();
					values[i][7] = obj.getBasePay() == null ? "" : obj.getBasePay().toEngineeringString();
					values[i][8] = obj.getCreateTime() == null ? "" : sdf.format(obj.getCreateTime());
					values[i][9] = obj.getCreator() == null ? "" : obj.getCreator();
				}
			}
			outPutExcel(response, title, fileName, sheetName, values);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
	}

	@ResponseBody
	@GetMapping("/excel.json")
	public void excel(HttpServletRequest request, HttpServletResponse response) {
		try {
			// excel标题
			String[] title = { "名称* ", "身份证号码* ", "员工账号* ","昵称", "手机号码* ", "部门编码* ", "密码* ", "二级权限密码* " ,"角色编码*" ,"岗位*（0总裁 1体系 2分公司/频道 3部门 4事业厅 5小组 6业务员 7 内容总裁 8 内容体系 9 内容频道 10 内容运营小组 11 内容主播）" };
			// excel文件名
			String fileName = "员工导入模板.xls";
			// sheet名
			String sheetName = "员工导入模板";
			String[][] values = new String[0][];
			outPutExcel(response, title, fileName, sheetName, values);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 从Excel导入数据字典
	 *
	 * @param file
	 * @param request
	 * @return
	 */
	@RequestMapping("/importExcel.json")
	@ResponseBody
	@SysLog(module = "基础模块", operationDesc = "导入员工")
	public BaseResponseBody importExcel(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			UserInfo creatUserInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			Integer prority = this.userInfoService.selectPrority();
			String fileName = file.getOriginalFilename();
			Workbook workbook = null;

			// 获取excel文件的io流
			InputStream is = file.getInputStream();
			// 根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
			if (fileName.endsWith("xls")) {
				// 2003
				workbook = new HSSFWorkbook(is);
			} else if (fileName.endsWith("xlsx")) {
				// 2007 及2007以上
				workbook = new XSSFWorkbook(is);
			}
			// 工作表
			Sheet sheet = workbook.getSheetAt(0);
			// 所有工作行
			int lastRowNum = sheet.getLastRowNum();

			List<UserInfo> list = new ArrayList<>();
			List<RoleRelUser> roleRelUserList = new ArrayList<>();

			for (int i = 1; i <= lastRowNum; i++) {
				String name = null;
				String idCardNum = null;
				String account = null;
				String nickName = null;
				String phone = null;
				String password = null;
				String permissionPassword = null;
				String deptId = null;
				String roleId = null;
				Integer type = null;
				Integer sourceType = null;

				// 每一行
				Row row = sheet.getRow(i);
				if (row == null) {
					break;
				}

				Cell cell0 = row.getCell(0);
				if (cell0 != null) {
					cell0.setCellType(CellType.STRING);
					name = row.getCell(0).getStringCellValue().trim();
					if (StringUtils.isBlank(name)) {
						return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.USER_NAME_NOT_NULL_ERROR.getMsg()), null);
					}
					UserInfo query = new UserInfo();
					query.setName(name);
					if (this.userInfoService.nameExist(query)) {
						continue;
					}
				}

				Cell cell1 = row.getCell(1);
				if (cell1 != null) {
					cell1.setCellType(CellType.STRING);
					idCardNum = cell1.getStringCellValue().trim();
					if (StringUtils.isBlank(idCardNum)) {
						return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.USER_IDCARDNUM_NOT_NULL_ERROR.getMsg()), null);
					}
				}

				Cell cell2 = row.getCell(2);
				if (cell2 != null) {
					cell2.setCellType(CellType.STRING);
					account = cell2.getStringCellValue().trim();
					if (StringUtils.isBlank(account)) {
						return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.USER_ACCOUNT_NOT_NULL_ERROR.getMsg()), null);
					}
					if (this.userInfoService.existAccount(account)) {
						continue;
					}
				}

				Cell cell3 = row.getCell(3);
				if (cell3 != null) {
					cell3.setCellType(CellType.STRING);
					nickName = cell3.getStringCellValue().trim();
				}

				Cell cell4 = row.getCell(4);
				if (cell4 != null) {
					cell4.setCellType(CellType.STRING);
					phone = cell4.getStringCellValue().trim();
					if (StringUtils.isBlank(phone)) {
						return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.USER_PHONE_NOT_NULL_ERROR.getMsg()), null);
					}
				}

				Cell cell5 = row.getCell(5);
				if (cell5 != null) {
					cell5.setCellType(CellType.STRING);
					String deptCode = cell5.getStringCellValue().trim();
					if (StringUtils.isBlank(deptCode)) {
						return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DEPT_CODE_ERROR.getMsg()), null);
					}
					Dept dept = this.deptService.selectByCode(deptCode);
					if (dept == null || dept.getIsDel()==1) {
						return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DEPT_CODE_ERROR.getMsg()), null);
					}
					sourceType = dept.getSourceSys();
					deptId = dept.getId();
				}

				Cell cell6 = row.getCell(6);
				if (cell6 != null) {
					cell6.setCellType(CellType.STRING);
					password = cell6.getStringCellValue().trim();
					if (StringUtils.isBlank(password)) {
						return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.USER_PASSWORD_NOT_NULL_ERROR.getMsg()), null);
					}
				}

				Cell cell7 = row.getCell(7);
				if (cell7 != null) {
					cell7.setCellType(CellType.STRING);
					permissionPassword = cell7.getStringCellValue().trim();
					if (StringUtils.isBlank(permissionPassword)) {
						return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.USER_PERMISSION_PASSWORD_NOT_NULL_ERROR.getMsg()), null);
					}
				}

				Cell cell8 = row.getCell(8);
				if (cell8 != null) {
					cell8.setCellType(CellType.STRING);
					String roleCode = cell8.getStringCellValue().trim();
					if (StringUtils.isBlank(roleCode)) {
						return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.ROLE_CODE_ERROR.getMsg()), null);
					}
					Role role = this.roleService.selectByCode(roleCode);
					if (role != null) {
						roleId = role.getId();
					}else {
						return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.ROLE_CODE_ERROR.getMsg()), null);
					}
				}

				Cell cell9 = row.getCell(9);
				if (cell9 != null) {
					cell9.setCellType(CellType.STRING);
					type = Integer.parseInt(cell9.getStringCellValue()) ;
					if (type==null) {
						return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.USER_TYPE_ERROR.getMsg()), null);
					}
				}

				// 判断手机号是否正确
				if(!phone.matches("^1(3|4|5|6|7|8|9)\\d{9}$")){
					return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RegisterResponseMsg.PHONE_FORMAT_ERROR.getMsg()), false);
				}
				// 判断身份证
				if(!idCardNum.matches("^\\d{15}\\d{2}[0-9xX]$")){
					return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RegisterResponseMsg.ID_CARD_NUM_FORMAT_ERROR.getMsg()), false);
				}

				UserInfo userInfo = new UserInfo();
				userInfo.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
				if (prority == null) {
					userInfo.setPriority(0);
				} else {
					prority = prority + 1;
					userInfo.setPriority(prority);
				}
				userInfo.setUserNum(this.userInfoService.selectUserNum());
				userInfo.setName(name);
				userInfo.setIdCardNum(idCardNum);
				userInfo.setAccount(account);
				userInfo.setNickName(nickName);
				userInfo.setPhone(phone);
				userInfo.setDeptId(deptId);
				userInfo.setSourceSys(sourceType);
				userInfo.setType(type);
				userInfo.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
				userInfo.setPermissionPassword(DigestUtils.md5DigestAsHex(permissionPassword.getBytes()));
				if(creatUserInfo!=null){
                    userInfo.setCreator(creatUserInfo.getName());
                    userInfo.setCreatorId(creatUserInfo.getId());
                }
				userInfo.setStatus(1);
				userInfo.setIsDel(0);
				// 获取邀请码前缀
				String recommendInitial = getDeptRecommendInitial(userInfo.getDeptId());
				userInfo.setOwnInvitationCode(createOwnInvitationCode(recommendInitial));
				userInfo.setCreateTime(new Date());

				RoleRelUser roleRelUser = new RoleRelUser();
				roleRelUser.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
				roleRelUser.setUserId(userInfo.getId());
				roleRelUser.setRoleId(roleId);
				roleRelUser.setCreateTime(new Date());
				this.userInfoService.insertBatchUser(userInfo,roleRelUser);
				// 关闭流
				is.close();
			}
			return new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), null);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询所有的子集id
	 *
	 * @param parentCode
	 * @param list
	 * @throws Exception
	 */
	private void selectDeptSon(String parentCode, List<String> list) throws Exception {
		List<Dept> deptList = this.deptService.selectByParentCode(parentCode);

		if (deptList != null) {
			for (Dept dept1 : deptList) {
				list.add(dept1.getId());
				selectDeptSon(dept1.getCode(), list);
			}
		}
	}

	/**
	 * 创建邀请码
	 *
	 * @return
	 */
	private String createOwnInvitationCode(String recommendInitial) throws Exception {
		int a = (int) (Math.random() * (9999 - 1000 + 1)) + 1000;
		if (this.userInfoService.existOwnInvitationCode(recommendInitial + a)) {
			return createOwnInvitationCode(recommendInitial);
		} else {
			return recommendInitial + a;
		}
	}

	/**
	 * 获取邀请码前缀
	 *
	 * @return
	 */
	private String getDeptRecommendInitial(String deptId) throws Exception {
		Dept dept = this.deptService.selectByPrimaryKey(deptId);

		if ( dept!=null &&dept.getType()!=null&& dept.getType() == 1 ) {
			if (StringUtils.isNotBlank(dept.getRecommendInitial())) {
				return dept.getRecommendInitial();
			} else {
				return "";
			}
		} else {
			Dept parentDept = this.deptService.selectByCode(dept.getParentCode());
			if (parentDept != null) {
				return getDeptRecommendInitial(parentDept.getId());
			} else {
				return "";
			}
		}
	}

	/**
	 * 输出Excel
	 *
	 * @param response
	 * @param title
	 * @param fileName
	 * @param sheetName
	 * @param values
	 * @throws IOException
	 */
	private void outPutExcel(HttpServletResponse response, String[] title, String fileName, String sheetName, String[][] values) throws IOException {
		// 创建HSSFWorkbook
		HSSFWorkbook wb = ExportExcelUtil.getHSSFWorkbook(sheetName, title, values, null);
		// 将文件存到指定位置
		this.setResponseHeader(response, fileName);
		OutputStream os = response.getOutputStream();
		wb.write(os);
		os.flush();
		os.close();
	}

	/**
	 * 发送响应流方法
	 *
	 * @param response
	 * @param fileName
	 */
	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.error(e.getMessage(), e);
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error(ex.getMessage(), ex);
		}
	}

	/**
	 * 查询组织架构接口
	 *
	 * @param code
	 * @param list
	 * @throws Exception
	 */
	private void selectSonId(String code, List<String> list) throws Exception {
		List<Dept> deptList = this.deptService.selectByParentCode(code);
		if (deptList != null) {
			for (Dept dept1 : deptList) {
				list.add(dept1.getId());
				selectSonId(dept1.getCode(), list);
			}
		}
	}
}
